import EventEmitter from "../eventEmitter";
import GraphBase from "../shape/graphBase";
import RectControlPoints from "./rectControlPoints";
import LineControlPoints from "./lineControlPoints";
export default class ControlPoints extends EventEmitter {
  target: HTMLCanvasElement;
  currentController: RectControlPoints | LineControlPoints | null = null;
  rectController!: RectControlPoints;
  lineController!: LineControlPoints;
  constructor(target: HTMLCanvasElement) {
    super();
    this.target = target;
    this.rectController = new RectControlPoints(target);
    this.lineController = new LineControlPoints(target);
    // 将实际控制器的事件转发出去
    this.rectController.on("redraw", () => {
      this.emit("redraw");
    });
    this.rectController.on(
      "resize",
      (rect: { x: number; y: number; width: number; height: number }) => {
        this.emit("resize", rect);
      }
    );
    this.rectController.on("drag", (translate: number[]) => {
      this.emit("drag", translate);
    });
    this.rectController.on("drop", () => {
      this.emit("drop");
    });
    this.lineController.on("redraw", () => {
      this.emit("redraw");
    });
    this.lineController.on("drag", (translate: number[]) => {
      this.emit("drag", translate);
    });
    this.lineController.on("drop", () => {
      this.emit("drop");
    });
  }
  setControlTarget(target: GraphBase[] | null | undefined) {
    // 根据当前控制的对象,替换控制器
    if (target && target.length > 1) {
      // 如果控制对象超过一个,则使用矩形控制器
      this.rectController.setActivity(true);
      this.currentController = this.rectController;
      this.lineController.setActivity(false);
    } else if (
      target &&
      target.length === 1 &&
      ["rect", "ellipse"].includes(target[0].type)
    ) {
      // 如果只控制一个矩形或者椭圆,,则使用矩形控制器
      this.rectController.setActivity(true);
      this.currentController = this.rectController;
      this.lineController.setActivity(false);
    } else if (
      target &&
      target.length === 1 &&
      ["polyline", "bezier"].includes(target[0].type)
    ) {
      // 如果只控制一条折线或者贝塞尔曲线,,则使用线形控制器
      this.lineController.setActivity(true);
      this.currentController = this.lineController;
      this.rectController.setActivity(false);
    } else {
      // 如果没有控制任何图元,则不使用控制器
      this.lineController.setActivity(false);
      this.rectController.setActivity(false);
      this.currentController = null;
    }
    this.currentController?.setControlTarget(target);
  }
  destroy() {
    this.currentController?.destroy();
    this.clear();
  }
  getHoverPoint() {
    return this.currentController?.getHoverPoint();
  }
  // 更新控制点的位置
  updateControlPoints(rect: {
    x: number;
    y: number;
    width: number;
    height: number;
  }) {
    this.currentController?.updateControlPoints(rect);
    this.drawControlPoints();
  }
  // 重绘控制点
  drawControlPoints() {
    this.currentController?.drawControlPoints();
  }
}
